﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace FlowersStore
{
	public partial class Cart : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			//((FlowersStore.SiteMaster)this.Master).FillCartItems();
		}

		private void CheckOrderItems()
		{
			if (Session["order"] != null)
			{
				UserOrder order = (UserOrder)Session["order"];
				CheckBox chb;
				ImageButton btnDel;
				foreach (var item in lvCart.Items)
				{
					btnDel = (ImageButton)item.FindControl("btnDeleteFromCart");
					long productId = long.Parse(btnDel.CommandArgument);
					chb = (CheckBox)item.FindControl("chbSelect");
					if (order.GetProductIds().Contains(productId))
						chb.Checked = true;
				}
			}
		}

		protected void lvCart_DataBound(object sender, EventArgs e)
		{
			//CheckOrderItems();
			//ShowTotalPrice();
			//Session["order"] = null;
		}


		protected void CartLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
		{
			if (Session["cart"] == null)
				Session["cart"] = new UserCart();
			if (Session["cart"] != null)
			{
				try
				{
					UserCart cart = (UserCart)Session["cart"];
					if (Session["order"] != null)
					{
						UserOrder order = (UserOrder)Session["order"];
						foreach (var pos in order.Positions)
						{
							cart.AddPosition(pos.ProductId, pos.Quantity);
						}
						Session["order"] = null;
					}
					long[] productIds = cart.GetProductIds().ToArray();
					FlowerStoreDataContext db = new FlowerStoreDataContext();

					var productsInCart = (from pr in db.Products
										  where productIds.Contains(pr.Product_id)
										  select
											new
											{
												id = pr.Product_id,
												name = pr.Product_name,
												img = pr.Product_thimbnailUrl,
												price = pr.Product_price,
												quantity = cart.GetProductQuantity(pr.Product_id)//,
												//totalPrice = cart.GetProductQuantity(pr.Product_id) * pr.Product_price
											}
										);
					e.Result = productsInCart;
				}
				catch { Response.Redirect("Default.aspx"); }
			}
			else
				e.Result = null;
			//else
			//    btnMakeOrder.Enabled = false;
		}

		protected string ComputeTotalPrice(object price, object quantity)
		{
			decimal pr = (decimal)price;
			int quant = (int)quantity;
			return string.Format("{0:n0}", pr * quant);
		}

		protected void chbSelectAll_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox chbAll = (CheckBox)sender;
			CheckBox chb;
			foreach (var item in lvCart.Items)
			{
				chb = (CheckBox)item.FindControl("chbSelect");
				chb.Checked = chbAll.Checked;
			}
			//btnMakeOrder.Enabled = chbAll.Checked;
			ShowTotalPrice();
		}

		protected void btnMakeOrder_Click(object sender, EventArgs e)
		{
			if (Session["cart"] != null)
			{
				UserCart cart = (UserCart)Session["cart"];
				UserOrder order = new UserOrder();
				CheckBox chb;
				TextBox tbQuantity;
				ImageButton btnDel;
				foreach (var item in lvCart.Items)
				{
					chb = (CheckBox)item.FindControl("chbSelect");
					if (chb.Checked)
					{
						tbQuantity = (TextBox)item.FindControl("TextBoxQuantity");
						btnDel = (ImageButton)item.FindControl("btnDeleteFromCart");
						int quant;
						long productId = long.Parse(btnDel.CommandArgument);
						if (!int.TryParse(tbQuantity.Text, out quant))
						{
							tbQuantity.Text = "1";
							quant = 1;
						}

						order.AddPosition(new ProductPosition { ProductId = productId, Quantity = quant });
						cart.DeletePosition(productId, int.MaxValue);
					}
				}
				if (order.Positions.Count > 0)
				{
					Session["order"] = order;
					Response.Redirect("CustomerData.aspx");
				}
			}
		}

		protected void btnDeleteFromCart_Click(object sender, EventArgs e)
		{
			if (Session["cart"] != null)
			{
				UserCart cart = (UserCart)Session["cart"];
				long productId = long.Parse(((ImageButton)sender).CommandArgument);
				cart.DeletePosition(productId, int.MaxValue);
				Response.Redirect("Cart.aspx");
			}
		}

		protected void chbSelect_CheckedChanged(object sender, EventArgs e)
		{			
			CheckBox chbAll=(CheckBox)lvCart.FindControl("chbSelectAll");			
			chbAll.Checked = false;
			ShowTotalPrice();
		}

		protected void ShowTotalPrice()
		{
			CheckBox chb;
			TextBox tbQuantity;
			ImageButton btnDel;
			Label lblPrice;
			decimal totalPrice = 0;
			foreach (var item in lvCart.Items)
			{
				chb = (CheckBox)item.FindControl("chbSelect");
				if (chb.Checked)
				{
					tbQuantity = (TextBox)item.FindControl("TextBoxQuantity");
					btnDel = (ImageButton)item.FindControl("btnDeleteFromCart");
					lblPrice = (Label)item.FindControl("ProductLabel");
					long productId = long.Parse(btnDel.CommandArgument);
					int quant;
					if (!int.TryParse(tbQuantity.Text, out quant))
					{
						tbQuantity.Text = "1";
						quant = 1;
					}
					using (FlowerStoreDataContext db = new FlowerStoreDataContext())
					{
						decimal price = (from p in db.Products
										 where p.Product_id == productId
										 select p.Product_price).Single();
						lblPrice.Text = string.Format("{0:n0}", price * quant);
						totalPrice += price * quant;
					}
				}
			}
			Label lblTotalPrice = (Label)lvCart.FindControl("lblTotalPrice");
			//btnMakeOrder.Enabled = totalPrice != 0;
			if (lblTotalPrice != null)
				lblTotalPrice.Text = string.Format("{0:n0}", totalPrice);
		}


	}
}